package com.hxd.otc.module.wallet.activity;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;

import com.hxd.otc.R;
import com.hxd.otc.base.BaseActivity;
import com.hxd.otc.module.wallet.bean.PayOrderResultBean;
import com.hxd.otc.module.wallet.bean.WalletOrderInfoBean;
import com.hxd.otc.module.wallet.contract.AECPayCaptureContract;
import com.hxd.otc.module.wallet.presenter.AECPayCapturePresenter;
import com.hxd.otc.other.MyCaptureFragment;
import com.hxd.otc.widget.TitleBar;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;

import java.util.List;

import butterknife.BindView;

/**
 * 作  者 :  卫广玉
 * 时  间 :  2018/6/7 18:16
 * 描  述 :  付款入口
 */
public class WalletPayCaptureActivity extends BaseActivity<AECPayCapturePresenter> implements AECPayCaptureContract.IView {

    @BindView(R.id.title_bar)
    TitleBar titleBar;
    private MyCaptureFragment captureFragment;

    private static final int PICK_IMAGE_REQUEST_CODE = 100;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_wallet_aec_pay_capture;
    }

    @Override
    protected AECPayCapturePresenter createPresenter() {
        return new AECPayCapturePresenter(this);
    }

    @Override
    protected void initView() {
        captureFragment = new MyCaptureFragment();
        // 为二维码扫描界面设置定制化界面
        CodeUtils.setFragmentArgs(captureFragment, R.layout.view_common_camera_pay);
        captureFragment.setAnalyzeCallback(analyzeCallback);
        getSupportFragmentManager().beginTransaction().replace(R.id.fl_my_container, captureFragment).commit();

        titleBar.getRightText().setText(R.string.wallet_qr_album);
        titleBar.getRightText().setTextColor(getResources().getColor(R.color.color_FF464E5F));
    }

    @Override
    protected void initData() {
    }

    @Override
    protected void initEvent() {
        titleBar.getRightText().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Matisse.from(WalletPayCaptureActivity.this)
                        .choose(MimeType.ofImage())
                        .countable(true)
                        .maxSelectable(1)
                        .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                        .thumbnailScale(0.85f)
                        .imageEngine(new GlideEngine())
                        .forResult(PICK_IMAGE_REQUEST_CODE);
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        /**
         * 选择系统图片并解析
         */
        if (requestCode == PICK_IMAGE_REQUEST_CODE) {
            if (data != null) {
                List<String> filePaths = Matisse.obtainPathResult(data);
                if (filePaths != null && filePaths.size() > 0) {
                    try {
                        CodeUtils.analyzeBitmap(filePaths.get(0), new CodeUtils.AnalyzeCallback() {
                            @Override
                            public void onAnalyzeSuccess(Bitmap mBitmap, String result) {
                                startConfirmActivity(result);
                            }

                            @Override
                            public void onAnalyzeFailed() {
                                showToast(getString(R.string.wallet_error_qr));
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 二维码解析回调函数
     */
    CodeUtils.AnalyzeCallback analyzeCallback = new CodeUtils.AnalyzeCallback() {
        @Override
        public void onAnalyzeSuccess(Bitmap mBitmap, String result) {
            startConfirmActivity(result);
        }

        @Override
        public void onAnalyzeFailed() {
            showToast(getString(R.string.wallet_error_qr));
            Handler handler = captureFragment.getHandler();
            Message msg = Message.obtain();
            msg.what = R.id.restart_preview;
            handler.sendMessageDelayed(msg, 2000);
        }
    };

    private void startConfirmActivity(String address) {
        if (address.contains("id:")) {//商户订单
            String id = address.substring(3, address.length());
            getMerchantsOrderInfo(id);
        } else if (address.contains("hengxunda:pay:preId:")) {//远程支付：可以获取到preId
            String preId = address.replace("hengxunda:pay:preId:", "");
            mPresenter.innerQueryOrder(preId);
        } else {
            Bundle bundle = new Bundle();
            bundle.putString(WalletPayConfirmActivity.EXTRA_ADDRESS, address);
            bundle.putInt(WalletPayConfirmActivity.EXTRA_PAY_TYPE, WalletPayConfirmActivity.PAY_TYPE_NORMAL);
            $startActivity(WalletPayConfirmActivity.class, bundle);
            finish();
        }
    }

    private void getMerchantsOrderInfo(String id) {
        showSpinnerDlg("", false);
        mPresenter.getMerchantsOrderInfo(id);
    }

    @Override
    public void getMerchantsOrderInfoSuccess(WalletOrderInfoBean walletOrderInfoBean) {
        dismissSpinnerDlg();
        if (walletOrderInfoBean != null) {
            Bundle bundle = new Bundle();
            bundle.putSerializable(WalletPayConfirmActivity.EXTRA_ORDER_INFO, walletOrderInfoBean);
            bundle.putInt(WalletPayConfirmActivity.EXTRA_PAY_TYPE, WalletPayConfirmActivity.PAY_TYPE_MERCHANTS);
            $startActivity(WalletPayConfirmActivity.class, bundle);
            finish();
        }
    }

    @Override
    public void getMerchantsOrderInfoFail(String errMessage) {
        dismissSpinnerDlg();
        showToast(errMessage);
        Handler handler = captureFragment.getHandler();
        Message msg = Message.obtain();
        msg.what = R.id.restart_preview;
        handler.sendMessageDelayed(msg, 2000);
    }

    @Override
    public void innerQueryOrderSuccess(PayOrderResultBean payOrderResultBean) {
        dismissSpinnerDlg();
        Bundle bundle = new Bundle();
        bundle.putSerializable(WalletPayConfirmActivity.EXTRA_ORDER_INFO, payOrderResultBean);
        bundle.putInt(WalletPayConfirmActivity.EXTRA_PAY_TYPE, WalletPayConfirmActivity.PAY_TYPE_API_PAY);
        $startActivity(WalletPayConfirmActivity.class, bundle);
        finish();
    }

    @Override
    public void innerQueryOrderFail(String errMessage) {
        dismissSpinnerDlg();
        showToast(errMessage);
        Handler handler = captureFragment.getHandler();
        Message msg = Message.obtain();
        msg.what = R.id.restart_preview;
        handler.sendMessageDelayed(msg, 2000);
    }
}
